package com.gradle.quartz.batch.controller;

import com.gradle.bean.employee.Employee;
import com.gradle.quartz.batch.service.EmployeeService;
import org.springframework.batch.core.*;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JobLauncher jobLauncher;
    @Autowired
    @Qualifier("csvToDbJob")
    private Job csvToDbJob;
    @Autowired
    @Qualifier("dbToDbjob")
    private Job dbToDbjob;
    @Autowired
    private JobExplorer jobExplorer;

    @GetMapping("/job/csvToDb")
    public ExitStatus csvToDb() {
        JobExecution execution = null;
        try {
            //employeeService.truncateEmployeeTemp();

            JobParametersBuilder parameters = new JobParametersBuilder(new JobParameters(),jobExplorer);
            parameters.addDate("date", new Date());
            Date date = new Date();
            parameters.addLong("time",date.getTime());
            parameters.getNextJobParameters(csvToDbJob).toJobParameters();
            //作业可以重复执行
            execution = jobLauncher.run(csvToDbJob, parameters.toJobParameters());
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert execution != null;
        return execution.getExitStatus();
    }
    @GetMapping("/job/dbToDb")
    public ExitStatus dbToDb() {
        JobExecution execution = null;
        try {
            //employeeService.truncateEmployeeTemp();

            JobParametersBuilder parameters = new JobParametersBuilder(new JobParameters(),jobExplorer);
            parameters.addDate("date", new Date());
            Date date = new Date();
            parameters.addLong("time",date.getTime());
            parameters.getNextJobParameters(dbToDbjob).toJobParameters();
            //作业可以重复执行
            execution = jobLauncher.run(dbToDbjob, parameters.toJobParameters());
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert execution != null;
        return execution.getExitStatus();
    }

    @GetMapping("/employee/queryEmployeeInfo")
    public List<Employee> queryEmployeeInfo(){
        List<Employee> employees = employeeService.queryEmployeeInfo();
        return employees;
    }

    @GetMapping("/dataInit")
    public String dataInit(){
        employeeService.dataInit();
        return "ok";
    }

}
